package entity

import "github.com/jinzhu/gorm"

type TagArticle struct {
	ID        uint
	TagId     uint
	ArticleId uint
}

func (ta TagArticle) CreateTagArticle(db *gorm.DB) error {
	err := db.Create(&ta).Error
	return err
}

func (ta TagArticle) GetTagNamesByArticleID(db *gorm.DB) ([]string, error) {
	var list []Tag
	err := db.Raw("select t.*from tag_article right join tag t on tag_article.tag_id = t.id where tag_article.article_id=?;", ta.ArticleId).Scan(&list).Error
	if err != nil {
		return nil, err
	}
	var res []string
	for _, v := range list {
		res = append(res, v.TagName)
	}
	return res, nil
}

func (ta TagArticle) GetByArticleId(db *gorm.DB) ([]TagArticle, error) {
	var list []TagArticle
	err := db.Where("article_id = ?", ta.ArticleId).Find(&list).Error
	return list, err
}

func (ta TagArticle) DeleteByArticleId(db *gorm.DB, id uint) error {
	return db.Where("article_id = ?", id).Delete(&ta).Error
}
